﻿//code by Heskey0
//https://space.bilibili.com/455965619
//https://github.com/Heskey0

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEngine;

namespace Teresa.Editor
{
    public class UIRootCodeGen
    {
        private static string _template = @"//code by Heskey0
//https://space.bilibili.com/455965619
//https://github.com/Heskey0

using System;
using System.Collections.Generic;
using Common.DesignPattern;
using Common.Extension;
using UnityEngine;

namespace Teresa
{
    public class UIManager : ManagerBase
    {
        private GameObject _root;
        private Dictionary<UILayer, GameObject> _layerNodeDic = new Dictionary<UILayer, GameObject>();

        public UIManager()
        {
            _root = Resources.Load<GameObject>(AppConfig.Path.UI.UIRootPath);
            GameObject.DontDestroyOnLoad(_root);
            for (int i = 0; i < (int) UILayer.End; i++)
            {
                var nodeLayer = (UILayer) i;
                var node = _root.transform.Find(nodeLayer.ToString()).gameObject;

                _layerNodeDic.Add(nodeLayer, node);
            }
        }

        public GameObject OpenPanel(string path, UILayer uiLayer)
        {
            return Resources.Load<GameObject>(path)
                .Instantiate()
                .SetParent(_layerNodeDic[uiLayer]);
        }

        public void ClosePanel(GameObject target)
        {
            GameObject.Destroy(target);
        }

        public void Clear(UILayer uiLayer)
        {
            _layerNodeDic[uiLayer].DestroyAllChildren();
        }
    }

    public enum UILayer
    {
        //gen_layer
        End,
    }
}";

        public static void GenerateCode(List<string> layerNameList)
        {
            if (File.Exists(AppConfig.Path.UI.UIManagerPath))
            {
                File.Delete(AppConfig.Path.UI.UIManagerPath);
            }

            StringBuilder sb = new StringBuilder("");
            for (int i = 0; i < layerNameList.Count; i++)
            {
                sb.Append(layerNameList[i]);
                sb.Append(",\n\t\t");
            }

            string genCode = string.Copy(_template);
            genCode = genCode.Replace("//gen_layer", sb.ToString());
            using (FileStream fs = File.Create(AppConfig.Path.UI.UIManagerPath))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.Write(genCode);
                    sw.Flush();
                }
            }

            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }
    }
}